package com.atguigu.gmall.common.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 远程调用拦截器
 * 拦截器 ： 页面微服务向购物车微服务发出请求之前被拦截下来 叫远程调用拦截器
 */
public class FeignInterceptor implements RequestInterceptor {

    //拦截器的执行方法,在远程调用之前执行
    //RequestTemplate : 参数1 ： 马上要发出的请求对象    Feign远程调用 Http请求
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //在springIOC容器, 任意位置都可以获取HttpServletRequest
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != servletRequestAttributes){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if (null != request){
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userId)){
                    //放到请求头中,请求再出发
                    requestTemplate.header("userId",userId);
                }

                if (!StringUtils.isEmpty(userTempId)){
                    //放到请求头中,请求再出发
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }
    }
}
